<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import type { FormRules } from 'element-plus'
import Editor from 'ckeditor5-custom-build/build/ckeditor'
import { uploadFile } from '@/utils/uploader'
// import ClassicEditor from '@ckeditor/ckeditor5-build-classic'
// import useEditorTool from '@/plugins/stratocirri-plus/hooks/useEditorTool'

// console.log(Editor)
interface Props {
  data?: Record<string, any> | never | null
  status: string
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add'
})

const formRef = ref()

const form = reactive<Record<string, any>>({
  // content: '<p>dfsadfasdf12431243</p'
  content: ''
})

class MyUploadAdapter {
    constructor( loader ) {
        // The file loader instance to use during the upload.
        this.loader = loader;
    }

    // Starts the upload process.
    async upload() {
      const file = await this.loader.file
      
        return  new Promise((resolve, reject) => {

                uploadFile({ file })
              .then((data: any) => {
                resolve({
                        default: data.url // 用实际图片地址替换
                    });
              })
              .catch((err) => {
                reject('Upload failed')
                console.error('Error:', err)
              })
            })
    }

    // Aborts the upload process.
    abort() {
        // Reject the promise returned from the upload() method.
        // server.abortUpload();
    }
}

const state: any = reactive({
  editor: Editor,
  editorData: '<p>Content of the editor.</p>',
  editorConfig: {
  }
})

// const { formatImage } = useEditorTool()

const rules = reactive<FormRules>({
  name: [{ required: true, message: '名称不能为空!', trigger: 'change' }],
  content: [{ required: true, message: '内容不能为空!', trigger: 'change' }]
})

const initForm = () => {
  if (props.data) {
    Object.keys(props.data).forEach((key: string) => {
      if (key === 'content') {
        if (disabled.value) {
          form[key] = formatImage(props.data![key])
        } else {
          form[key] = props.data![key]
        }
      } else {
        form[key] = props.data![key]
      }
    })
  }
}

const formatImage = (html: any) => {
  // html = '<img src="image1.jpg" data-a="aa"><img src="image22.jpg" data-a="a2a"><p>Some text with no image</p><img width="500px" src="i23mage3.jpg"  1  >'
  const regex = /(<img.*?src=")(.*?)(".*?>)/g
  const matches = html.match(regex)
    
  if (matches && matches.length) {
    matches.forEach((v: any) => {
        html = html.replace(v, v.replace('img', "img style='width: 100%;height: auto;'"))
    })
  }

  return html
}

const formatForm = () => {
  const result: Record<string, any> = {}
  Object.keys(form).forEach((key: string) => {
    result[key] = form[key]
  })
  return result
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}

const disabled = computed(() => {
  return props.status === 'read'
})

const onEditorReady = editor => {
  //自定义图片上传
  editor.plugins.get('FileRepository').createUploadAdapter = loader => {
    return new MyUploadAdapter(loader)
  }
}


defineExpose({
  submitForm
})

onMounted(() => {
  initForm()
})
</script>

<template>
  <div class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="base-form">
      <el-form-item label="名称：" prop="name">
        <el-input v-model="form.name" type="text" placeholder="请输入名称" maxlength="20" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="内容：" prop="content" style="width: 100%">
        <ckeditor v-if="!disabled" :editor="state.editor" v-model="form.content" :config="state.editorConfig" @ready="onEditorReady"></ckeditor>
        <div v-if="disabled" v-dompurify-html="form.content" style="width: 100%; word-wrap: break-word"></div>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.base-form {
  width: 100%;
  @include flex(row, flex-start, center);
  flex-wrap: wrap;
  .el-form-item {
    // width: 50%;
    padding-right: 50px;
    box-sizing: border-box;
  }
}
</style>
